package com.qfedu.factory;

import com.qfedu.service.AccountService;
import com.qfedu.util.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


//用来生产代理对象
public class BeanFactory {

    private AccountService accountService;

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    private TransactionManager transactionManager;

    //生成代理对象
    public AccountService getBean(){
        //代理对象
        AccountService o = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
            //增强业务逻辑
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if ("transfer".equals(method.getName())){
                    try {
                        //开启事务
                        transactionManager.beginTransaction();
                        //目标方法执行
                        method.invoke(accountService,args);
                        //提交事务
                        transactionManager.commit();
                    } catch (Exception e) {
                        //回滚事务
                        transactionManager.rollback();
                        e.printStackTrace();
                    } finally {
                        transactionManager.release();
                    }
                }
                return null;
            }
        });
        return  o;

    }



}
